/*
 * Created on May 17, 2004
 */
package org.vectrics.recruiter.web;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.vectrics.SystemException;
import org.vectrics.company.Company;
import org.vectrics.company.Sector;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobFunction;
import org.vectrics.recruiter.job.JobStatusType;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.recruiter.user.JobAgent;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;

/**
 * @author mmoore
 */
public class RecruitWebTestPrepare {
    private Log log = LogFactory.getLog(RecruitWebTestPrepare.class);

    public RecruitWebTestPrepare() {
        super();
    }

    private void getTestElements(Element parentElement) {
        try {
            Date now = new Date();
            Domain domain = ThreadProperties.getDomain();
            Sector sector = CoreServiceLocator.getCompanyService().findSector("telecom");

            Company company = CoreServiceLocator.getCompanyService().createCompany(domain,
                    "Test company - " + now.getTime(), null, sector);
            String jobFunctionCode = TestDataConstants.JOB_AGENT_1_JOB_FUNCTION_CODE;
            JobFunction jobFunction = RecruitServiceLocator.getJobProvider().findFunction(jobFunctionCode);
            if (jobFunction == null)
                throw new SystemException("Could not find job function code: " + jobFunctionCode);

            Element userElement = parentElement.addElement(TestDataConstants.USER_XML_ELEMENT_NAME);
            Person authPerson = createTestUserIfNotExist(userElement);
            CandidateInfo candidateInfo = RecruitServiceLocator.getRecruitUserService().createCandidateInfoIfNotExist(
                    authPerson);
            if (candidateInfo.getJobAgents().size() == 0) {
                JobAgent jobAgent = candidateInfo.addJobAgent();
                jobAgent.setActive(true);
                jobAgent.setCandidateInfo(candidateInfo);
                jobAgent.setName(TestDataConstants.JOB_AGENT_1_NAME);
                jobAgent.addJobFunction(jobFunction);
                Location jobAgentLocation = CoreServiceLocator.getLocationService().findLocation(
                        TestDataConstants.JOB_AGENT_1_LOCATION_ID);
                if (jobAgentLocation == null) {
                    throw new SystemException("Could not find location: " + TestDataConstants.JOB_AGENT_1_LOCATION_ID);
                }
                jobAgent.addLocation(jobAgentLocation);

            }
            RecruitServiceLocator.getRecruitUserService().updateCandidateInfo(candidateInfo);

            Element jobElement = parentElement.addElement(TestDataConstants.JOB_XML_ELEMENT_NAME);
            Job job = RecruitServiceLocator.getJobProvider().findCreateJobWithRefCode(domain, "test-job", authPerson);
            job.setStatus(RecruitServiceLocator.getJobProvider().findJobStatusType(JobStatusType.STATUS_POSTED,
                    job.getDomain()), authPerson, RecruitServiceLocator.getJobProvider().findDefaultStatusReason(
                    job.getDomain(), null, JobStatusType.STATUS_POSTED));
            job.setDescription(TestDataConstants.JOB_DESCRIPTION);
            job.setTitle(TestDataConstants.JOB_TITLE);
            job.setFunction(jobFunction);
            job.setCompany(company);
            RecruitServiceLocator.getJobProvider().updateJob(job);
            jobElement.addAttribute("id", job.getId().toString());
        } catch (Exception ex) {
            log.error("Exception reporting on test data", ex);
        }
    }

    public Person createTestUserIfNotExist(Element userElement) {
        Person testUser = CoreServiceLocator.getPersonService().findCreatePersonWithUserName(
                ThreadProperties.getDomain(), TestDataConstants.USER_NAME);
        testUser.setFirstName(TestDataConstants.USER_FIRST_NAME);
        testUser.setLastName(TestDataConstants.USER_LAST_NAME);
        testUser.setMiddleName(TestDataConstants.USER_MIDDLE_NAME);
        CoreServiceLocator.getPersonService().updatePerson(testUser);
        userElement.addAttribute("id", testUser.getId().toString());
        return (testUser);
    }

    public void handlePrepRequest(Request request, HttpServletResponse response) throws IOException {
        Date now = new Date();
        long time = now.getTime();
        Document responseDocument = DocumentFactory.getInstance().createDocument();
        Element mainElement = responseDocument.addElement("test-data");
        getTestElements(mainElement);
        String responseText = responseDocument.asXML();
        log.info("Response: " + responseText);

        log.debug("Setting content type");
        response.setContentType("xml");

        log.debug("Writing bytes to response");
        log.debug("Size of byte array = " + responseText.length());
        response.getOutputStream().write(responseText.getBytes());
        response.setContentLength(responseText.length());

        log.info("Flushing response");
        response.getOutputStream().flush();
    }

}
